package org.ricks.ioc.utils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Logger {

    // 新增 ANSI 颜色常量
    private static final String ANSI_RESET = "\u001B[0m";
    private static final String ANSI_RED = "\u001B[31m";
    private static final String ANSI_GREEN = "\u001B[32m";
    private static final String ANSI_YELLOW = "\u001B[33m";
    private static final String ANSI_CYAN = "\u001B[36m";

    // 日志级别枚举
    public enum Level {
        DEBUG, INFO, WARN, ERROR
    }

    private static Level currentLevel = Level.INFO; // 默认级别
    private static final DateTimeFormatter FORMATTER =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
    private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{\\}");


    // 设置日志级别
    public static void setLevel(Level level) {
        currentLevel = level;
    }

    // 参数化日志格式化
    private static String formatMessage(String message, Object... args) {
        if (args == null || args.length == 0) return message;

        Matcher matcher = PLACEHOLDER_PATTERN.matcher(message);
        StringBuffer sb = new StringBuffer();
        int index = 0;

        while (matcher.find() && index < args.length) {
            String replacement = (args[index] != null) ? args[index].toString() : "null";
            matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
            index++;
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

//    // 日志输出核心方法（新增参数支持）
//    private static void log(Level level, String message, Throwable throwable, Object... args) {
//        if (level.ordinal() < currentLevel.ordinal()) return;
//
//        String formattedMessage = formatMessage(message, args);
//        StackTraceElement caller = getCallerInfo();
//        String className = caller.getClassName();
//        String methodName = caller.getMethodName();
//        String timestamp = FORMATTER.format(LocalDateTime.now());
//
//        // 核心优化点：固定宽度对齐
//        String levelStr = String.format("%-7s", level);
//        String prefix = timestamp + " [" + levelStr + "] " + className + "#" + methodName + " (Line " + caller.getLineNumber() + ") - ";
//
//        System.out.println(prefix + formattedMessage);
//        if (throwable != null) {
//            throwable.printStackTrace(System.err);
//        }
//    }

    private static StackTraceElement getCaller() {
        StackTraceElement[] stack = Thread.currentThread().getStackTrace();
        for (int i = 0; i < stack.length; i++) {
            String className = stack[i].getClassName();
            // 跳过日志工具类及JDK内部类
            if (className.startsWith("org.ricks.ioc.utils") ||
                    className.startsWith("java.lang.Thread")) {
                continue;
            }
            return stack[i]; // 返回第一个非日志框架的调用点
        }
        return new StackTraceElement("Unknown", "unknown", "Unknown", 0);
    }


    private static void log(Level level, String message, Throwable throwable, Object... args) {
        if (level.ordinal() < currentLevel.ordinal()) return;

        // 根据级别选择颜色
        String color = switch (level) {
            case ERROR -> ANSI_RED;
            case WARN -> ANSI_YELLOW;
            case INFO -> ANSI_GREEN;
            case DEBUG -> ANSI_CYAN;
            default -> ANSI_RESET;
        };

        String formattedMessage = formatMessage(message, args);
        StackTraceElement caller = getCaller();
        String timestamp = FORMATTER.format(LocalDateTime.now());

        String levelStr = String.format("%-7s", level);
        // 核心修改：为日志级别和消息添加颜色
        String prefix = timestamp + " [" + color + levelStr + ANSI_RESET + "] - ";
        // 消息部分也着色（可选）
        String coloredMessage = color + formattedMessage + ANSI_RESET;

        System.out.println(prefix + coloredMessage);
        if (throwable != null) {
            throwable.printStackTrace(System.err);
        }
    }



    // 快速日志方法（新增参数化版本）
    public static void debug(String message) {
        log(Level.DEBUG, message, null);
    }
    public static void debug(String message, Object... args) {
        log(Level.DEBUG, message, null, args);
    }

    public static void info(String message) {
        log(Level.INFO, message, null);
    }
    public static void info(String message, Object... args) {
        log(Level.INFO, message, null, args);
    }

    public static void warn(String message) {
        log(Level.WARN, message, null);
    }
    public static void warn(String message, Object... args) {
        log(Level.WARN, message, null, args);
    }

    public static void error(String message, Throwable throwable) {
        log(Level.ERROR, message, throwable);
    }
    public static void error(String message, Throwable throwable, Object... args) {
        log(Level.ERROR, message, throwable, args);
    }


    public static void main(String[] args) {
        // 简单日志
        Logger.debug("Service initialized");

// 参数化日志
        Logger.info("User {} logged in from {}", "Alice", "192.168.1.100");

// 带异常的日志
        try {
            processOrder();
        } catch (Exception ex) {
            Logger.error("Order {} processing failed", ex, 11);
        }

    }

    public static void processOrder() {
        throw new RuntimeException("你好！");
    }
}
